package com.ukefu.webim.service.sms;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.sms.SmsService;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.SystemMessageRepository;
import com.ukefu.webim.web.model.SmsResult;
import com.ukefu.webim.web.model.SmsTemplate;
import com.ukefu.webim.web.model.SystemMessage;

@Service("dysms")
public class AliSmsImpl implements SmsService {
	
	public static ObjectMapper objectMapper = new ObjectMapper();

	@Override
	public SmsResult send(SystemMessage systemMessage, SmsResult result, String phone, SmsTemplate tp , Map<String, Object> values)
			throws Exception {
		// 设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		// 初始化ascClient需要的几个参数
		final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名（接口地址固定，无需修改）
		// 替换成你的AK
		final String accessKeyId = systemMessage.getAppkey();// 你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = systemMessage.getAppsec();// 你的accessKeySecret，参考本文档步骤2
		result.setAppkey(accessKeyId);
		result.setSubtime(new Date());
		// 初始化ascClient,暂时不支持多region（请勿修改）
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		CommonRequest request = new CommonRequest();

		request.setDomain(domain);
		request.setVersion("2017-05-25");
		request.setAction("SendSms");
		request.setDomain(domain);
		// 使用post提交
		request.setMethod(MethodType.POST);
		request.putQueryParameter("RegionId", "cn-hangzhou");
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		request.putQueryParameter("PhoneNumbers", phone);
		// 必填:短信签名-可在短信控制台中找到
		request.putQueryParameter("SignName", systemMessage.getSign());
		// 必填:短信模板-可在短信控制台中找到
		request.putQueryParameter("TemplateCode", systemMessage.getTpcode());
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		request.putQueryParameter("TemplateParam", UKTools.getTemplet(tp.getTemplettext(),values));
		// 可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
		// request.setSmsUpExtendCode("90997");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		request.putQueryParameter("OutId", "yourOutId");
		// 请求失败这里会抛ClientException异常
		try {
			CommonResponse sendSmsResponse = acsClient.getCommonResponse(request);
			String checkstr = systemMessage.getResultcheck() ;
			if(StringUtils.isBlank(checkstr)) {
				checkstr = "OK" ;
			}
			if (sendSmsResponse.getData() != null && sendSmsResponse.getData().indexOf(checkstr) >= 0) {
				result.setSendresult(sendSmsResponse.getData());
				result.setSendok(true);
			} else if (!StringUtils.isBlank(sendSmsResponse.getData())) {
				result.setSendresult(sendSmsResponse.getData());
			}
		} catch (Exception ex) {
			result.setSendresult(ex.getMessage());
			throw ex;
		} finally {
			result.setSendtime(new Date());
		}
		return result;
	}

	@Override
	public SmsResult checkReach(SmsResult result) throws Exception {
		if (!StringUtils.isBlank(result.getSendresult()) && !StringUtils.isBlank(result.getServerid())) {
			SystemMessage systemMessage = null;
			if((systemMessage = (SystemMessage) CacheHelper.getSystemCacheBean().getCacheObject(result.getServerid(), result.getOrgi())) == null) {
				systemMessage = UKDataContext.getContext().getBean(SystemMessageRepository.class).findByIdAndOrgi(result.getServerid(),result.getOrgi()) ;
				if(systemMessage!=null) {
					CacheHelper.getSystemCacheBean().put(result.getServerid(),systemMessage, result.getOrgi()) ;
				}
			}
			if(systemMessage==null) {
				return result;
			}
			@SuppressWarnings("unchecked")
			Map<String, Object> resultMap = objectMapper.readValue(result.getSendresult(), Map.class);
			if (resultMap != null && resultMap.get("BizId")!=null) {
				// 替换成你的AK
				final String accessKeyId = systemMessage.getAppkey();// 你的accessKeyId,参考本文档步骤2
				final String accessKeySecret = systemMessage.getAppsec();// 你的accessKeySecret，参考本文档步骤2
				// 初始化ascClient,暂时不支持多region（请勿修改）
				IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
				IAcsClient acsClient = new DefaultAcsClient(profile);
				// 组装请求对象
				CommonRequest request = new CommonRequest();
				
				// 设置超时时间-可自行调整
				System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
				System.setProperty("sun.net.client.defaultReadTimeout", "10000");
				
				request.setMethod(MethodType.POST);
				request.setDomain("dysmsapi.aliyuncs.com");
				request.setVersion("2017-05-25");
				request.setAction("QuerySendDetails");
				request.putQueryParameter("RegionId", "cn-hangzhou");
				request.putQueryParameter("CurrentPage", "1");
				request.putQueryParameter("PageSize", "10");
				request.putQueryParameter("PhoneNumber", result.getPhonenumber());
				SimpleDateFormat dateFormate = new SimpleDateFormat("yyyyMMdd") ;
				request.putQueryParameter("SendDate", dateFormate.format(new Date()));
				request.putQueryParameter("BizId", resultMap.get("BizId").toString());
				
				try {
					CommonResponse sendSmsResponse = acsClient.getCommonResponse(request);
					if (!StringUtils.isBlank(sendSmsResponse.getData())) {
						JSONObject jsonDate = new JSONObject(sendSmsResponse.getData());
						if(jsonDate.getJSONObject("SmsSendDetailDTOs").getJSONArray("SmsSendDetailDTO")!=null && jsonDate.getJSONObject("SmsSendDetailDTOs").getJSONArray("SmsSendDetailDTO").length() > 0){
							JSONObject smsSendDetailDTO = jsonDate.getJSONObject("SmsSendDetailDTOs").getJSONArray("SmsSendDetailDTO").getJSONObject(0);
							if (smsSendDetailDTO!=null && smsSendDetailDTO.getInt("SendStatus")==3 && "DELIVERED".equals(smsSendDetailDTO.getString("ErrCode")) && !StringUtils.isBlank(smsSendDetailDTO.getString("ReceiveDate"))) {
								SimpleDateFormat datesFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
								result.setReachtime(datesFormate.parse(smsSendDetailDTO.getString("ReceiveDate")));
								if (!StringUtils.isBlank(smsSendDetailDTO.getString("Content"))) {
									result.setSendcontent(smsSendDetailDTO.getString("Content"));
									result.setDescription(null);
								}
							}
						}
					}
				} catch (Exception e) {
					result.setDescription(e.toString());
				}
			}
		}
		return result;
	}

}
